/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.stakeholder;

import entity.ImageEntity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.PhaseEvent;
import javax.faces.event.ValueChangeEvent;
import org.primefaces.event.FileUploadEvent;
import session.stateless.MediaSessionBean;
import session.stateless.StakeholderSessionBeanStateless;
import session.stateless.SystemMessagesBean;
import util.entityhelper.StakeholderAccountState;
import util.localization.WebLocalization;

/**
 *
 * @author Amelia
 */
@ManagedBean
@RequestScoped
public class MediaManagedBean implements Serializable {

    @EJB
    private MediaSessionBean mediaSessionBean;
    @EJB
    private StakeholderSessionBeanStateless stakeholderSessionBean;
    //Exception
    @EJB
    private SystemMessagesBean systemMessages;
    //User Selected Locale
    private String preferredLocale;
    private WebLocalization localization;
    private Long stakeholderID;
    private String imageFilePath;
    private StakeholderAccountState stakeholderAccountState;
    private List<ImageEntity> imageList;
    private ImageEntity[] selectedImageList;

    /** Creates a new instance of MediaManagedBean */
    public MediaManagedBean() throws KeyStoreException {
        /*LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        KeyStore.getInstance("JKS");
        /* END LOCALIZATION */
    }

    public void initView(PhaseEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);

        stakeholderID = (Long) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholderId");
        if (stakeholderID == null) {
            //Session not save. (redirect Stakeholder to login.
            String nextPage = FacesContext.getCurrentInstance().getExternalContext().encodeActionURL(FacesContext.getCurrentInstance().getApplication().getViewHandler().getActionURL(FacesContext.getCurrentInstance(), "/StakeholderLogin.xhtml"));
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect(nextPage);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        try {
            stakeholderAccountState = stakeholderSessionBean.getStakeholderPortalInfoById(stakeholderID);
            if (imageList == null) {
                getImageList();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void handleImageUpload(FileUploadEvent event) throws AbortProcessingException, NoSuchAlgorithmException {

        try {
            String strDirectory = stakeholderAccountState.getUsername();
            String filePath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/images/upload/media/" + strDirectory);
            System.out.println("filePath: " + filePath + " created");
            File file = new File(filePath);
            if (!file.exists()) {
                if ((new File(filePath)).mkdir()) {
                    System.out.println("Directory: " + strDirectory + " created");
                }
            }
            File result = new File(filePath + System.getProperty("file.separator") + event.getFile().getFileName());
            System.out.println("result: " + result + " created");
            FileOutputStream out = new FileOutputStream(result);


            int a;
            int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];

            InputStream is = event.getFile().getInputstream();

            while (true) {
                a = is.read(buffer);

                if (a < 0) {
                    break;
                }

                out.write(buffer, 0, a);
                out.flush();
            }

            out.close();
            is.close();

            imageFilePath = "/images/upload/media/" + strDirectory + "/" + event.getFile().getFileName();
            System.out.println("imagefilepath: " + imageFilePath);
            int pos = event.getFile().getFileName().lastIndexOf("."); //position of ".", to get the file extension
            if (mediaSessionBean.addImage(stakeholderID, imageFilePath, event.getFile().getFileName().substring(pos))) {
                String statusMessage = systemMessages.getSystemMessage("MEDIA_UPLOADED_SUCCESSFULLY", preferredLocale);
                String statusMessage1 = systemMessages.getSystemMessage("MEDIA_IS_UPLOADED", preferredLocale);
                FacesMessage msg = new FacesMessage(statusMessage, event.getFile().getFileName() + " " + statusMessage1);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("imageFilePath", imageFilePath);
            }

        } catch (IOException e) {
            String statusMessage = systemMessages.getSystemMessage("MEDIA_FILEUPLOAD_IO_ERROR", preferredLocale);
            FacesContext.getCurrentInstance().addMessage("sPortalform", new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, statusMessage));
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void saveCaption(ValueChangeEvent event) {
        String caption = event.getNewValue().toString();
        ImageEntity selectedImage = (ImageEntity) event.getComponent().getAttributes().get("selectedImage");
        selectedImage.setCaption(caption);
        System.out.println("Image Caption: " + selectedImage.getCaption());
        try {
            if (!mediaSessionBean.addImageCaption(selectedImage, caption)) {
                String statusMessage = systemMessages.getSystemMessage("MEDIA_ADDCAPTION_FAILED", preferredLocale);
                FacesContext.getCurrentInstance().addMessage("sPortalform", new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, null));
            } else {
                String statusMessage = systemMessages.getSystemMessage("MEDIA_ADDCAPTION_SUCCESS", preferredLocale);
                FacesContext.getCurrentInstance().addMessage("sPortalform", new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, null));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void removeImage() {
        try {
            if (!mediaSessionBean.removeImage(selectedImageList)) {
                String statusMessage = systemMessages.getSystemMessage("MEDIA_REMOVEIMAGE_FAILED", preferredLocale);
                FacesContext.getCurrentInstance().addMessage("sPortalform", new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, null));
            } else {
                String statusMessage = systemMessages.getSystemMessage("MEDIA_REMOVEIMAGE_SUCCESS", preferredLocale);
                FacesContext.getCurrentInstance().addMessage("sPortalform", new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, null));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public String getImageFilePath() {
        return imageFilePath;
    }

    public void setImageFilePath(String imageFilePath) {
        this.imageFilePath = imageFilePath;
    }

    public List<ImageEntity> getImageList() {
        imageList = new ArrayList<ImageEntity>();
        try {
            imageList = mediaSessionBean.getImage(stakeholderID);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return imageList;
    }

    public void setImageList(List<ImageEntity> imageList) {
        this.imageList = imageList;
    }

    public ImageEntity[] getSelectedImageList() {
        return selectedImageList;
    }

    public void setSelectedImageList(ImageEntity[] selectedImageList) {
        this.selectedImageList = selectedImageList;
    }
}
